package it.inefficienza.test.spring.controller;

import it.inefficienza.test.spring.model.Contact;
import it.inefficienza.test.spring.service.ContactService;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class ContactController {
 
    @Autowired
    private ContactService contactService;
 
	@RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {
 
        map.put("contact", new Contact());
        map.put("contactList", contactService.listContact());
    	map.put("modifyURL", "/add"); 
    	map.put("modifyLabel", "label.addcontact");    	

        return "contact";
    }
 
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact") Contact contact) {
 
        contactService.addContact(contact);
 
        return "redirect:/index";
    }

    @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId") Long contactId) {
 
        contactService.removeContact(contactId);
 
        return "redirect:/index";
    }

    @RequestMapping(value = "/edit/{contactId}", method = RequestMethod.GET)
    public String selectContact(@PathVariable("contactId") Long contactId, Map<String, Object> map) {
        map.put("contact", contactService.getContact(contactId));
        map.put("contactList", contactService.listContact());
    	map.put("modifyURL", "/edit"); 
    	map.put("modifyLabel", "label.updatecontact");    	
    	return "contact";
    }    

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String updateContact(@ModelAttribute("contact") Contact contact, Map<String, Object> map) {
    	contactService.updateContact(contact);
        return "redirect:/index";
    }    

    
    // ~~~~~~~~~~~~ GETTERS AND SETTERS ~~~~~~~~~~~~~~~ //
	public void setContactService(ContactService contactService) {
		this.contactService = contactService;
	}
    
    
}